package com.yanqu.road.dao.impl.patrons;

import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.impl.TempDao;
import com.yanqu.road.entity.player.UserPatronsSimple;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class PatronsSimpleDaoImpl extends TempDao {

	public Map<Long, Map<Integer, UserPatronsSimple>> getUserPatronsSimpleMap() {
		Map<Long, Map<Integer, UserPatronsSimple>> dataMap = new ConcurrentHashMap<>();
		ResultSet rs = null;
		CallableStatement call = null;
		String sql = "select * from t_u_patrons";
		try {
			getDb().setConnName(DbNameStrategy.getUserDb());
			call = getDb().getConnection().prepareCall(sql);
			rs = call.executeQuery();
			while (rs.next()) {
				UserPatronsSimple data = parseUserPatronsSimple(rs);
				if(!dataMap.containsKey(data.getUserId())){
					dataMap.put(data.getUserId(), new ConcurrentHashMap<>());
				}
				dataMap.get(data.getUserId()).put(data.getPatronsId(), data);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			getDb().closeConnection(call, rs);
		}
		return dataMap;
	}

	private UserPatronsSimple parseUserPatronsSimple(ResultSet rs) throws SQLException {
		UserPatronsSimple data = new UserPatronsSimple();
		data.setUserId(rs.getLong("userId"));
		data.setPatronsId(rs.getInt("patronsId"));
		String value = rs.getString("ability");
		if(!StringUtils.isNullOrEmpty(value)){
			data.setAbility(new BigInteger(value));
		}
		data.setTradeWarLoseScoreReduce(rs.getLong("tradeWarLoseScoreReduce"));
		return data;
	}
}
